#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>

using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

int longestZigZag(TreeNode* root) {
    int res = 0;
    auto dfs = [&](auto&& dfs, TreeNode* root)->vector<int> {
        int left = 0, right = 0;
        if (root->left)
        {
            auto t = dfs(dfs, root->left);
            left = t[1] + 1;
        }
        if (root->right)
        {
            auto t = dfs(dfs, root->right);
            right = t[0] + 1;
        }
        res = max(res, max(left, right));
        return { left,right };
    };

    dfs(dfs, root);
    return res;
}